<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-card class="chart-container">
          <div slot="header" class="clearfix" style="font-size:15px;">
            <b>地块选择：</b><el-select v-model="field_id" clearable filterable placeholder="选择地块" @change="changeField">
              <el-option
                v-for="(item,index) in fieldsFilter"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="气象站" name="first"><state :device="qxz" /></el-tab-pane>
            <el-tab-pane label="墒情站" name="second"><state :device="sqz" /></el-tab-pane>
          </el-tabs>
          <div class="h12" />
          <el-divider content-position="left"><b class="color-primary">电磁阀</b></el-divider>
          <state :device="fkq" />
          <action :device="fkq" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card
          class="chart-container"
          style="padding:0;margin:12px 0;"
        >
          <div slot="header" class="clearfix" style="font-size:15px;">
            <b>生育期：</b><el-select v-model="crop_growth_id" clearable filterable placeholder="选择生育期" @change="changeCropGrowth">
              <el-option
                v-for="(item,index) in cropGrowthes"
                :key="index"
                :label="item.stage_name"
                :value="index"
              />
            </el-select>
          </div>
          <div class="qxz">
            <el-divider content-position="left"><b class="color-primary">土壤湿度变化</b></el-divider>
            <ve-line
              v-if="results.length > 0"
              :height="chartHeight"
              :data="chartData"
              :extend="chartExtend"
              :settings="chartSettings"
            />
          </div>
          <div class="qxz">
            <el-divider content-position="left"><b class="color-primary">灌溉 + 降雨 信息</b></el-divider>
            <ve-histogram :data="chartDataIrrRainfall" :height="chartHeight" :extend="chartExtend" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <mqtt-container
      ref="mqttContainer"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { convertArr2Obj, removeEmptyField } from '@/utils'
import MqttContainer from '@/components/MqttContainer'
import { getAll } from '@/api/fieldSensorDaily'
import { getAll as getIrrRaifall } from '@/api/plantDetail'
import State from './components/State'
import Action from './components/Action'
export default {
  components: {
    MqttContainer,
    State,
    Action
  },
  data() {
    return {
      irrRainfalls: [],
      results: [],
      chartSettings: {},
      chartHeight: '350px',
      chartExtend: {
        series: {
          showSymbol: false
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '2%',
          top: '12%',
          containLabel: true
        }
      },
      activeName: 'first',
      field: {},
      field_id: '',
      qxz_sn: '',
      sqz_sn: '',
      fkq_sn: '',
      qxz: {},
      sqz: {},
      fkq: {},
      crop_growth_id: '',
      cropGrowthes: []
    }
  },
  computed: {
    ...mapGetters(['fields', 'project', 'devices', 'devicesObj']),
    fieldsFilter() {
      return this.fields.filter((val) => {
        return +val.project_id === +this.project.id
      })
    },
    fieldsFilterObj() {
      return convertArr2Obj(this.fieldsFilter, 'id')
    },
    chartData() {
      const fields = [
        { namekey: 'gdate', name: '日期' },
        { namekey: 'val1_avg', name: '10cm平均(%)' },
        { namekey: 'val2_avg', name: '30cm平均(%)' },
        { namekey: 'val3_avg', name: '50cm平均(%)' },
        { namekey: 'val4_avg', name: '70cm平均(%)' }
      ]

      const rows = []
      this.results.forEach((item, index) => {
        rows.push({
          '日期': item.gdate,
          '10cm最高(%)': item.rows[0].val_max || 0,
          '10cm最低(%)': item.rows[0].val_min || 0,
          '10cm平均(%)': item.rows[0].val_avg || 0,
          '30cm最高(%)': item.rows[1] && item.rows[1].val_max || 0,
          '30cm最低(%)': item.rows[1] && item.rows[1].val_min || 0,
          '30cm平均(%)': item.rows[1] && item.rows[1].val_avg || 0,
          '50cm最高(%)': item.rows[2] && item.rows[2].val_max || 0,
          '50cm最低(%)': item.rows[2] && item.rows[2].val_min || 0,
          '50cm平均(%)': item.rows[2] && item.rows[2].val_avg || 0,
          '70cm最高(%)': item.rows[3] && item.rows[3].val_max || 0,
          '70cm最低(%)': item.rows[3] && item.rows[3].val_min || 0,
          '70cm平均(%)': item.rows[3] && item.rows[3].val_avg || 0
        })
      })

      return {
        columns: fields.map(val => val.name),
        rows
      }
    },
    chartDataIrrRainfall() {
      const fields = [
        { namekey: 'created_at', name: '计划灌溉日期' },
        { namekey: 'rainfall', name: '降雨量(mm)' },
        { namekey: 'amount_irr', name: '灌溉量(mm)' }
      ]

      return {
        columns: fields.map(val => val.name),
        rows: this.irrRainfalls.map((item) => {
          const temp = {}
          fields.forEach((citem) => {
            temp[citem.name] = item[citem.namekey]
            if (citem.namekey === 'created_at') {
              temp[citem.name] = item[citem.namekey].substr(0, 10)
            }
          })
          return temp
        })
      }
    }
  },
  watch: {
    field: {
      handler(newVal) {
        if (newVal.id) {
          this.cropGrowthes = newVal.plant.cropGrowthes || []
          this.crop_growth_id = ''
          this.getDevices(newVal)
          this.getList({ field_id: newVal.id })
          this.getIrrRainfall({ plant_id: newVal.plant.id })
        }
      },
      immediate: true
    },
    devicesObj: {
      handler(newVal) {
        this.qxz = newVal[this.qxz_sn]
        this.sqz = newVal[this.sqz_sn]
        this.fkq = newVal[this.fkq_sn]
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.field = this.fieldsFilter[0]
    this.field_id = this.field.id || ''
  },
  methods: {
    async getIrrRainfall(params) {
      const { data } = await getIrrRaifall(removeEmptyField(params))
      this.irrRainfalls = data.data
    },
    async getList(params) {
      const { data } = await getAll(removeEmptyField(params))
      this.results = data
    },
    changeField(val) {
      this.field = this.fieldsFilterObj[val]
    },
    changeCropGrowth(val) {
      const cropGrowth = this.cropGrowthes[val]
      this.getList({ field_id: this.field.id, gdate: [cropGrowth.stage_start, cropGrowth.stage_end] })
      this.getIrrRainfall({
        plant_id: this.field.plant.id,
        created_at: [cropGrowth.stage_start, cropGrowth.stage_end]
      })
    },
    getDevices(field) {
      this.qxz_sn = field.weather_sn
      const devicesObj = convertArr2Obj(field.devices, 'dclass')
      this.sqz_sn = devicesObj[8].serialno
      this.fkq_sn = devicesObj[13].serialno
      this.qxz = this.devicesObj[this.qxz_sn]
      this.sqz = this.devicesObj[this.sqz_sn]
      this.fkq = this.devicesObj[this.fkq_sn]
    }
  }
}
</script>

<style lang="scss" scoped>
.chart-container {
  height: calc(100vh - 74px);
  margin: 12px;
  padding: 0;
}
</style>
